Sorting in Pandas¶

There are two kinds of sorting available in pandas:

  1. Sort by index
  2. Sort by value
In [1]:
#import the libraries
import pandas as pd 
import numpy as np

Sorting for Series¶

Sort by index

  • Sorting by index can be done by using sort_index command.
In [2]:
s=pd.Series([67,45,23,6,12,57],index=["e","d","a","f","b","c"])
s
Out[2]:
e    67
d    45
a    23
f     6
b    12
c    57
dtype: int64
In [3]:
s.sort_index()
Out[3]:
a    23
b    12
c    57
d    45
e    67
f     6
dtype: int64

Sorting by Value¶

Sorting by value can be done by sort_value command.

In [4]:
s.sort_values()
Out[4]:
f     6
b    12
a    23
d    45
c    57
e    67
dtype: int64

Sorting for DataFrame¶

Sorting by index¶

In [5]:
data = {'Name':pd.Series(['Akshay','Rajat','Robin','Kapil','James','Cyril']),'Age':pd.Series([25,26,29,27,23,21]),'Rating':pd.Series([4.23,2.35,1.56,3.20,4.62,3.99])}
df = pd.DataFrame(data,index=[5,3,2,4,1])
df
Out[5]:
Name Age Rating
5 Cyril 21 3.99
3 Kapil 27 3.20
2 Robin 29 1.56
4 James 23 4.62
1 Rajat 26 2.35
In [6]:
df.sort_index()
Out[6]:
Name Age Rating
1 Rajat 26 2.35
2 Robin 29 1.56
3 Kapil 27 3.20
4 James 23 4.62
5 Cyril 21 3.99

Sort the Data By Columns¶

In [7]:
df.sort_index(axis=1)
Out[7]:
Age Name Rating
5 21 Cyril 3.99
3 27 Kapil 3.20
2 29 Robin 1.56
4 23 James 4.62
1 26 Rajat 2.35

By default, sorting is sorted in ascending order.But sorting can also be done in descending order, by using ascending = False.

In [8]:
df.sort_index(ascending=False)
Out[8]:
Name Age Rating
5 Cyril 21 3.99
4 James 23 4.62
3 Kapil 27 3.20
2 Robin 29 1.56
1 Rajat 26 2.35

Sorting the values by Age column¶

In [9]:
df.sort_values(by="Age")
Out[9]:
Name Age Rating
5 Cyril 21 3.99
4 James 23 4.62
1 Rajat 26 2.35
3 Kapil 27 3.20
2 Robin 29 1.56

Ascending Order¶

In [10]:
df.sort_values(by="Age",ascending=True)
Out[10]:
Name Age Rating
5 Cyril 21 3.99
4 James 23 4.62
1 Rajat 26 2.35
3 Kapil 27 3.20
2 Robin 29 1.56

Descending Order¶

In [11]:
df.sort_values(by="Age",ascending=False)
Out[11]:
Name Age Rating
2 Robin 29 1.56
3 Kapil 27 3.20
1 Rajat 26 2.35
4 James 23 4.62
5 Cyril 21 3.99